'use strict'

const AV = require('leanengine')
const Promise = require('bluebird')
const matchIns = require('../libs/Match')
const api = require('../wechat/wechatAPI')
const WECHAT_CONFIG = require('../wechat/config')

var func = {

  create (req) {
    var teams = req.params.teams
    var umpire = req.params.umpire
    var scoringSys = req.params.scoringSys
    var discipline = req.params.discipline
    var bestOf = req.params.bestOf
    var Match = AV.Object.extend('Match')
    var match = new Match
    return match.save({
      teams,
      creator: {
        __type: 'Pointer',
        objectId: req.user.id,
        className: '_User'
      },
      umpire,
      team1: teams[0],
      team2: teams[1],
      scoringSys,
      discipline,
      bestOf,
      state: 'preparing'
    })
  },

  invite (req) {
    var MatchInvitation = AV.Object.extend('MatchInvitation')
    var matchInvitation = new MatchInvitation
    var roomId = req.params.roomId
    var invitee = req.params.invitee
    return matchInvitation.save({
      roomId: roomId,
      invitee: invitee.map(x => x.objectId),
      inviter: {
        __type: 'Pointer',
        className: '_User',
        objectId: req.user.id
      }
    }).then(function () {
      invitee.forEach(x => {
        var content = `${WECHAT_CONFIG.host}/#!/newMatch?roomId=${roomId}`
        api.sendText(x.openid, content, new Function)
      })
      return Promise.resolve()
    })
  },

  getMatch (req) {
    var matchObjId = req.params.matchObjId
    var cql = `select * from Match where objectId = '${matchObjId}'`
    return AV.Query.doCloudQuery(cql).then(ret => {
      if (!ret || !ret.results || !ret.results.length) return Promise.reject()
      return Promise.resolve(ret.results[0])
    })
  },

  save (req) {
    var matchObjId = req.params.matchObjId
    var games = req.params.matchGames
    var duration = req.params.matchDuration
    var scores = req.params.matchScores
    var winnerIndex = req.params.winnerIndex
    var withdrawlIndex = req.params.withdrawlIndex
    var cql = `select * from Match where objectId = '${matchObjId}'`
    var ins = matchIns({games, duration, scores})
    var scoringArr = ins.getScoringArr()
    var maxConsecutivePoints = ins.getMaxConsecutivePoints()
    console.log('hello', maxConsecutivePoints)
    return AV.Query.doCloudQuery(cql).then(ret => {
      var teams = ret.results[0].get('teams')
      return ret.results[0].save({
        games,
        duration,
        scores,
        eachGameScores: games.map(el => _.map(el.scores, x => x)),
        withdrawl: teams[withdrawlIndex] || [],
        winner: teams[winnerIndex],
        scoringArr,
        maxConsecutivePoints,
        state: 'complete'
      })
    })
  }

}


AV.Cloud.define('match', function (req, res) {
  var promise
  if (!req.user) {
    promise = Promise.reject({
      msg: 'not loged in'
    })
  } else {
    promise = func[req.params.method](req)
  }
  return promise.then(function (ret) {
    res.success(ret)
  }).catch(function (err) {
    console.log(err)
    res.error(err)
  })
})
